package com.kdyzm.ruoyi.vue.gen.manager;

import com.kdyzm.ruoyi.vue.gen.common.constant.GenConstants;
import com.kdyzm.ruoyi.vue.gen.common.exception.CustomException;
import com.kdyzm.ruoyi.vue.gen.domain.GenTable;
import com.kdyzm.ruoyi.vue.gen.mapper.GenTableMapper;
import com.kdyzm.ruoyi.vue.gen.properties.GenConfig;
import com.kdyzm.ruoyi.vue.gen.service.IGenTableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kdyzm
 */
@Component
@Slf4j
public class GenManager {

    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private GenConfig genConfig;

    @Autowired
    private GenTableMapper genTableMapper;

    public void generate() {
        //第一步：检查是否存在历史数据并删除
        String tableName = genConfig.getTableName();
        GenTable req = new GenTable();
        req.setTableName(tableName);
        List<GenTable> genTables = genTableMapper.selectGenTableList(req);
        if (!CollectionUtils.isEmpty(genTables)) {
            log.warn("表{}生成数据已存在，即将删除历史数据" , tableName);
            Long[] array = new Long[genTables.size()];
            genTables.stream().map(GenTable::getTableId).collect(Collectors.toList()).toArray(array);
            genTableService.deleteGenTableByIds(array);
        }
        //第二步：导入表结构
        GenTable genTable;
        GenTable genSubTable = new GenTable();
        String subTableName = genConfig.getSubTableName();
        if (StringUtils.isEmpty(subTableName)) {
            genTable = genTableService.selectTableByName(tableName);
        } else {
            //主子表信息
            String subTableFkName = genConfig.getSubTableFkName();
            if (StringUtils.isEmpty(subTableFkName)){
                throw new CustomException("subTableFkName为空");
            }
            genTable = genTableService.selectTableByName(tableName);
            genSubTable = genTableService.selectTableByName(subTableName);

            genTable.setSubTable(genSubTable);
            genTable.setTplCategory(GenConstants.TPL_SUB);
            genTable.setSubTableName(subTableName);
            genTable.setSubTableFkName(subTableFkName);

        }
        // 查询表信息
        List<GenTable> tableList = new ArrayList<>();
        tableList.add(genTable);

        if (!StringUtils.isEmpty(subTableName)){
            tableList.add(genSubTable);
        }

        if (!CollectionUtils.isEmpty(tableList)) {
            genTableService.importGenTable(tableList);
            //第三步：生成压缩文件
            byte[] data = genTableService.downloadCode(tableName);
            genCode("ruoyi.zip" , data);
            log.info("生成文件位置:" + System.getProperty("user.dir") + "/ruoyi.zip");

        } else {
            log.info("table not found: " + tableName);
        }

    }

    /**
     * 生成zip文件
     *
     * @param fileName 目标压缩文件名
     * @param data     字节数组
     */
    public void genCode(String fileName, byte[] data) {
        try {
            IOUtils.write(data, new FileOutputStream(new File(fileName)));
        } catch (IOException e) {
            log.error("" , e);
        }
    }

}
